import React from "react";

import { Collapse ,Alert } from 'antd';

import { ajax ,isNull,isEmpty} from '../../common';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

const Panel = Collapse.Panel;

/**
 * 表单字段数据源配置页面
 */
export default class ConfigProductUIComponentDataSourcePanel extends React.Component {

	state = {
		datasource : null
	}

	componentDidMount(){
		const {datasourceId} = this.props;
		if(isNull(datasourceId) === false && isEmpty(datasourceId) === false){
			ajax('PRODUCT/UI/productUIList/getById',{id : datasourceId},(data) => {
				this.setState({datasource : data});
			});
		}
	}

	actionHandler = (actionEvent) => {

		const { selectIds, fieldDatasourceListRef } = this;

		return {
			chooseUIList : () => {
				const selectedDatasource = fieldDatasourceListRef.getSelectedDatas();
				let dataSource = null;
				if(isNull(actionEvent.params) === false){
					dataSource = actionEvent.params;
					this.setState({datasource : actionEvent.params});
				}
				else if(selectedDatasource.length > 0){
					dataSource = selectedDatasource[0];
					this.setState({datasource : selectedDatasource[0]});
				}

				if(this.props.onDatasourceChange){
					this.props.onDatasourceChange(dataSource);
				}
			
			},
			clearUIList : () => {
				if(this.props.onDatasourceChange){
					this.props.onDatasourceChange(null);
				}
				this.setState({datasource : null});
			}
		}
	}

	getDataSource = (cb) => {
		const {datasource} = this.state;
		//const {formField} = this.props;
		//formField.dataSource = isNull(datasource) ? '' : datasource.id;
		if(cb){
			cb(datasource);
		}
		return datasource;
	}

	render () {

		const {datasource} = this.state;

		const tableProps = {
			bordered : false,
			ref: (inst) => { this.fieldDatasourceListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'chooseProductUIListListActionGroup',
			rowActionGroupId: 'chooseProductUIListListActionGroup',
			tableConfigId: 'productUIListTable',
			dataUrl: 'PRODUCT/UI/productUIList/query',
			selectMode: 'single',
			searchFormId: 'productUIListSearchForm',
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('ok');
				}
				else {
					topToolBar.disable('ok');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
		};

		return (
			<React.Fragment>
				<Alert 
					message="当前数据源"
					description={isNull(datasource) === false ? datasource.code : '无'}
					type="info"
				/>
				<Collapse >
					<Panel header="可选数据源列表" key="1">
						<UIDataTableView {...tableProps}/>
					</Panel>
				</Collapse>
			</React.Fragment>
			
		);
	}
}